package com.example.saifly.inPageMy;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.OSS.OssHelper;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.common.Util.RegxUtil;
import com.example.saifly.R;
import com.example.saifly.login.LoginActivity;
import com.example.saifly.login.PatientInfomation;
import com.lljjcoder.citypickerview.widget.CityPicker;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.qqtheme.framework.picker.NumberPicker;
import cn.qqtheme.framework.picker.OptionPicker;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class HomeSetActivity extends Activity{
    @Override
    protected int getContentLayoutId()
    {
        return R.layout.activity_home_set;
    }

    private CityPicker cityPicker;   //地址选择器实例

    //用户个人信息
    private CircleImageView civSymble;
    private EditText etName;  //用户名
    private EditText etPhoneNum; //手机号
    private TextView tvCity;  //所在城市
    private TextView tvSex;  //性别
    private TextView tvBirthday;  //出生年月
    private TextView tvHeight;  //身高
    private TextView tvWeight;  //体重

    private TextView tvPhoneText;    //紧急联系人手机号or患者手机号

    private RelativeLayout rlSymble; //头像
    private RelativeLayout rlCity;  //所在城市
    private RelativeLayout rlSex;  //性别
    private RelativeLayout rlBirthday;  //出生年月
    private RelativeLayout rlHeight;  //身高
    private RelativeLayout rlWeight;  //体重

    private TextView tvSave;
    private ImageView ivReturn;
    private Button btExit;

    private boolean isTape=true,isname=true,isphone=true;
    private boolean isSave=false;
    private boolean isModify=false;

    private PatientInfomation user=new PatientInfomation();

    //初始化全局变量，稍后用于退出时清空uid和identity
    private SharedPreferences sharedPreferences= MyApplication.getContext().getSharedPreferences("config",Context.MODE_PRIVATE);
    private String phoneNumber=sharedPreferences.getString("uid","default");;

    private String modifyImageUrl;       //修改后的数据
    private String modifyName;
    private String modifyPhoneNumber;
    private String modifyCity;
    private String modifySex;
    private String modifyBirthday;
    private Integer modifyHeight;
    private Integer modifyWeight;

    private String initialImageUrl;     //修改前的数据
    private String initialName;
    private String initialPhoneNumber;
    private String initialCity;
    private String initialSex;
    private String initialBirthday;
    private Integer initialHeight;
    private Integer initialWeight;

    private LocalMedia localPath;
    private String localUrl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    protected void init() {
        super.init();

        civSymble=findViewById(R.id.set_avatar);
        etName=findViewById(R.id.set_name);
        etPhoneNum=findViewById(R.id.set_phoneNumber);
        tvCity=findViewById(R.id.set_addr);
        tvSex=findViewById(R.id.set_sex);
        tvBirthday=findViewById(R.id.set_birthday);
        tvHeight=findViewById(R.id.set_hight);
        tvWeight=findViewById(R.id.set_weight);
        tvSave=findViewById(R.id.set_save);
        ivReturn=findViewById(R.id.set_return);
        btExit=findViewById(R.id.set_exit);

        tvPhoneText=findViewById(R.id.set_phone_text);
        if(sharedPreferences.getString("identity","default").equals("patient"))
        {
            tvPhoneText.setText("紧急联系人手机号");
        }
        else
        {
            tvPhoneText.setText("相关联患者手机号");
            etPhoneNum.setEnabled(false);
        }

        rlSymble=findViewById(R.id.rl_set_avatar);
        rlCity=findViewById(R.id.set_city_rl);
        rlSex=findViewById(R.id.set_sex_rl);
        rlBirthday=findViewById(R.id.set_birthday_rl);
        rlHeight=findViewById(R.id.set_height_rl);
        rlWeight=findViewById(R.id.set_weight_rl);

        tvSave=findViewById(R.id.set_save);
        ivReturn=findViewById(R.id.set_return);
        btExit=findViewById(R.id.set_exit);

        rlSymble.setOnClickListener(new addListeners());
        rlSex.setOnClickListener(new addListeners());
        rlCity.setOnClickListener(new addListeners());
        rlBirthday.setOnClickListener(new addListeners());
        rlHeight.setOnClickListener(new addListeners());
        rlWeight.setOnClickListener(new addListeners());
        tvSave.setOnClickListener(new addListeners());
        ivReturn.setOnClickListener(new addListeners());
        doJump();

        patientInfomationInit();

    }

//    @Override
//    protected void onStart() {
//        super.onStart();
//        patientInfomationInit();
//    }

    public void patientInfomationInit()
    {
        initialImageUrl = sharedPreferences.getString("portrait","default");
//        Log.d("头像", "logData: "+sharedPreferences.getString("portrait","default"));

        initialName = sharedPreferences.getString("nickname", "default");

        if(sharedPreferences.getString("identity","default").equals("patient"))  //患者显示紧急联系人手机号
        {
            initialPhoneNumber = sharedPreferences.getString("contactPhone", "default");
        }
        else
        {
            initialPhoneNumber=sharedPreferences.getString("uid","default");   //家属显示患者手机号
        }
        initialCity = sharedPreferences.getString("city", "湖南省-长沙市-岳麓区");
        initialSex = sharedPreferences.getString("sex", "男");
        initialBirthday = sharedPreferences.getString("birthday", "2000-01-01");
        initialHeight = sharedPreferences.getInt("height", 165);
        initialWeight = sharedPreferences.getInt("weight", 60);

        modifyImageUrl = sharedPreferences.getString("portrait","default");
//        Log.d("头像", "logData: "+sharedPreferences.getString("portrait","default"));

        modifyName = sharedPreferences.getString("nickname", "default");
        modifyPhoneNumber = sharedPreferences.getString("contactPhone", "default");
        modifyCity = sharedPreferences.getString("city", "湖南省-长沙市-岳麓区");
        modifySex = sharedPreferences.getString("sex", "男");
        modifyBirthday = sharedPreferences.getString("birthday", "2000-01-01");
        modifyHeight = sharedPreferences.getInt("height", 165);
        modifyWeight = sharedPreferences.getInt("weight", 60);

        Glide.with(HomeSetActivity.this).load("https://lztoos.oss-cn-shenzhen.aliyuncs.com/"+initialImageUrl).into(civSymble);
        etName.setText(initialName);
        etPhoneNum.setText(initialPhoneNumber);
        tvCity.setText(initialCity);
        tvSex.setText(initialSex);
        tvBirthday.setText(initialBirthday);
        tvHeight.setText(initialHeight.toString()+"cm");
        tvWeight.setText(initialWeight.toString()+"kg");

    }


    /**
     * 上传到oss的方法,在网络请求函数的一开始调用，也就是RetrofitHelper的之前
     * ossPath=upload();
     */
    private String upload() {
        return OssHelper.uploadImage(HomeSetActivity.this, localUrl);
    }

    private void initChooseImage() {
        PictureSelector.create(HomeSetActivity.this)
                .openGallery(PictureMimeType.ofImage())//选择图片资源
                .selectionMode(PictureConfig.SINGLE)//单选图片
                .previewImage(true)//可预览图片
                .isCamera(true)//可拍照
                .enableCrop(true)//允许裁剪
                .compress(true)//压缩
                .withAspectRatio(1, 1)//裁剪比1：1
                .hideBottomControls(false)//显示底部控制栏
                .isGif(false)//不显示gif图
                .freeStyleCropEnabled(true)//可拖拽裁剪框
                .circleDimmedLayer(true)//圆形裁剪框
                .showCropFrame(false)//圆形建议取消边框
                .minimumCompressSize(100)//图片如果小于100kb就不压缩
                .rotateEnabled(true)//可旋转
                .scaleEnabled(true)//可放大缩小
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    localPath = selectList.get(0);
                    // 例如 LocalMedia 里面返回四种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // 4.media.getAndroidQToPath();为Android Q版本特有返回的字段，此字段有值就用来做上传使用
                    if (localPath.isCompressed()) {
                        localUrl = localPath.getCompressPath();
                    } else if (localPath.isCut()) {
                        localUrl = localPath.getCutPath();
                    } else {
                        localUrl = localPath.getPath();
                    }
                    Glide.with(HomeSetActivity.this).load(localUrl).into(civSymble);
                    break;
            }
        }
    }
    //设置页面跳转逻辑
    private void doJump() {
        btExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Logout();
                    }
                }).start();
                //修改全局变量 uid和identity
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("uid","1");
                editor.putString("identity","patient");
                editor.apply();

                Intent intent=new Intent(HomeSetActivity.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }

    private void Logout(){

        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        modifyPatientInfomation apiHomeSetData=retrofit.create(modifyPatientInfomation.class);
//        Log.d("registerhaha", "logData: "+jsonObject);

        Call<ResponseBody> call=apiHomeSetData.Logout();
        final Response<ResponseBody> response;
        try{
            response=call.execute();
            if(response.body()!=null){
                Log.d("logoutttt", "Logout: "+response.body().string());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private interface modifyPatientInfomation
    {
        @Headers({"Content-Type:application/json"})
        @POST("/manage/modifyPatientInfomation")
        Call<ResponseBody> HomeSetData(@Body JSONObject jsonObject);

        @Headers({"Content-Type:application/json"})
        @POST("/logout")
        Call<ResponseBody> Logout();

    }

    private void HomeSetData(PatientInfomation patientInfomation)   //向服务器发送更改的个人信息
    {
        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        modifyPatientInfomation apiHomeSetData=retrofit.create(modifyPatientInfomation.class);

        JSONObject jsonObject=new JSONObject();
        String jsonString = JSON.toJSONString(patientInfomation);
//        Log.d("registerhahah", "logData: "+jsonString);
        jsonObject.put("patientInformation",jsonString);
//        Log.d("registerhaha", "logData: "+jsonObject);

        Call<ResponseBody> call=apiHomeSetData.HomeSetData(jsonObject);
        final Response<ResponseBody> response;
        try {
            response=call.execute();
            JSONObject result=JSON.parseObject(response.body().string());
            Log.d("registerhaha", "logData: "+result);
            if(result.getInteger("code")==1){
                //获取的code为1 说明修改成功
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(HomeSetActivity.this,"修改成功",Toast.LENGTH_SHORT).show();

                        sharedPreferences.edit()
                                .putString("nickname",modifyName)
                                .putString("contactPhone",modifyPhoneNumber)
                                .putString("sex",modifySex)
                                .putString("city",modifyCity)
                                .putString("birthday",modifyBirthday)
                                .putString("portrait",modifyImageUrl)
                                .putInt("height",modifyHeight)
                                .putInt("weight",modifyWeight)
                                .apply();

                        isSave=true;
                        finish();
                    }
                });
            }
            else{
                //修改失败
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(HomeSetActivity.this,"修改失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(HomeSetActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    /**
     * 昵称不能为空
     */
    public void nameNotNull()
    {
        if (etName.getText().toString().equals(""))
        {
            Toast.makeText(HomeSetActivity.this,"用户名不能为空",Toast.LENGTH_SHORT).show();
            isname=false;
        }
        else
        {
            isname=true;
        }
    }
    /**
     * 手机号输入不能为空
     */
    public void phoneNotNull()
    {
        if (etPhoneNum.getText().toString().equals(""))
        {
            Toast.makeText(HomeSetActivity.this,"手机号不能为空",Toast.LENGTH_SHORT).show();
            isTape=false;
        }
        else
        {
            isTape=true;
        }
    }
    /*
     * 判断手机号的正确性
     */
    public void phoneJudge()
    {
        if(RegxUtil.isPhone(etPhoneNum.getText().toString())==false)
        {
            Toast.makeText(HomeSetActivity.this,"请输入正确的手机号",Toast.LENGTH_SHORT).show();
            isphone=false;
        }
        else {
            isphone=true;
        }
    }

    /**
     * 性别选择器
     */
    private void initSexPicker()
    {
        OptionPicker picker = new OptionPicker(this, new String[]{
                "男", "女"
        });
        picker.setOffset(1);
        picker.setSelectedIndex(0);
        picker.setTextSize(15);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option) {
                tvSex.setText(option);
            }
        });
        picker.show();
    }


    //地址选择器
    public void initCityPicker(){
        cityPicker = new CityPicker.Builder(HomeSetActivity.this)
                .textSize(20)
                .title("地址选择")
                .backgroundPop(0xa0000000)
                .titleBackgroundColor("#f8f8f8")
                .titleTextColor("#000000")
                .confirTextColor("#000000")
                .cancelTextColor("#000000")
                .province("xx省")
                .city("xx市")
                .district("xx区")
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                String province = citySelected[0];
                String city = citySelected[1];
                String district = citySelected[2];

                tvCity.setText(province+"-"+city+"-"+district);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    //出生日期选择器
    private void initDatePicker() {
        Calendar now =  Calendar. getInstance();
        new DatePickerDialog(HomeSetActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                        tvBirthday.setText(year + "-" + month + "-" + day);
                    }
                },
                now.get(Calendar.YEAR),
                now.get(Calendar.MONTH),
                now.get(Calendar.DAY_OF_MONTH)).show();
    }

    //身高选择器

    private void initHeightPicker() {
        NumberPicker heightPicker = new NumberPicker(this);
        heightPicker.setOffset(2);//偏移量
        heightPicker.setRange(100, 200);//数字范围
        heightPicker.setSelectedItem(165);
        heightPicker.setLabel("厘米");
        heightPicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener()
        {
            @Override
            public void onOptionPicked(String option)
            {
                tvHeight.setText(option+"cm");
            }
        });
        heightPicker.show();
    }

    //体重选择器
    private void initWeightPicker() {
        NumberPicker weightPicker = new NumberPicker(this);
        weightPicker.setOffset(2);//偏移量
        weightPicker.setRange(10, 400);//数字范围
        weightPicker.setSelectedItem(60);
        weightPicker.setLabel("千克");
        weightPicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option)
            {
                tvWeight.setText(option+"kg");
            }
        });
        weightPicker.show();
    }

    public void Sure () {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if(isModify==true&&isSave==false)
        {
            builder.setTitle("修改未保存，确定退出？");
            builder.setPositiveButton("确定", (dialog, which) -> {
                dialog.dismiss();
                finish();
            })
                    .setNegativeButton("取消", (dialog, which) -> {
                        //取消对话框，返回界面
                        dialog.cancel();
                    }).create().show();
            //只有点击按钮才行，点击空白无用
            builder.setCancelable(false);
        }
        else finish();
    }


    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType)  throws ParseException
    {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }

    private int StringToInteger(String str)
    {
        int temp;
        String tmp="";
        for(int i=0;i<str.length();i++)
        {
            if (str.charAt(i)>'9'||str.charAt(i)<'0') {
                break;
            }
            else
            {
                tmp+=str.charAt(i);
            }
        }
        temp=Integer.parseInt(tmp);
        return temp;
    }

    private class addListeners implements View.OnClickListener
    {
        @Override
        public void onClick (View v)
        {
            switch (v.getId())
            {
                case R.id.set_save:
                    nameNotNull();
                    phoneNotNull();
                    phoneJudge();
                    if(localUrl!=null) {
                        modifyImageUrl = OssHelper.uploadImage(HomeSetActivity.this, localUrl);
//                        Log.d("yonghu", "logData: "+modifyImageUrl);
                    }else{
                        modifyImageUrl=sharedPreferences.getString("portrait","default");
                    }
                    user.setPatientAvatar(modifyImageUrl);
                    user.setPatientPhone(phoneNumber);
                    modifyName=etName.getText().toString().trim();
                    user.setPatientName(modifyName);
                    modifyPhoneNumber=etPhoneNum.getText().toString().trim();
                    user.setPatientContactPhone(modifyPhoneNumber);
                    modifyCity=tvCity.getText().toString().trim();
                    user.setPatientHome(modifyCity);
                    modifySex=tvSex.getText().toString().trim();
                    user.setPatientSex(modifySex);
                    modifyBirthday=tvBirthday.getText().toString().trim();
                    try
                    {
                        user.setPatientBirthday(stringToDate(modifyBirthday,"yyyy-MM-dd"));
                    }
                    catch (ParseException e)
                    {
                        e.printStackTrace();
                    }
                    modifyHeight=StringToInteger(tvHeight.getText().toString().trim());
                    modifyWeight=StringToInteger(tvWeight.getText().toString().trim());
                    user.setPatientHeight(modifyHeight);
                    user.setPatientWeight(modifyWeight);
//                    Log.d("yonghu", "logData: "+user.toString());
                    if (isTape==true&&isname==true&&isphone==true)
                    {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                HomeSetData(user);
                            }
                        }).start();
                    }
                    break;
                case R.id.set_return:
                    if(localUrl!=null) {
                        modifyImageUrl = OssHelper.uploadImage(HomeSetActivity.this, localUrl);
//                        Log.d("yonghu", "logData: "+modifyImageUrl);
                    }else{
                        modifyImageUrl=sharedPreferences.getString("portrait","default");
                    }
                    modifyName=etName.getText().toString().trim();
                    modifyPhoneNumber=etPhoneNum.getText().toString().trim();
                    modifyCity=tvCity.getText().toString().trim();
                    modifySex=tvSex.getText().toString().trim();
                    modifyBirthday=tvBirthday.getText().toString().trim();
                    modifyHeight=StringToInteger(tvHeight.getText().toString().trim());
                    modifyWeight=StringToInteger(tvWeight.getText().toString().trim());
                    if(modifyImageUrl.equals(initialImageUrl) && modifyName.equals(initialName) && modifyPhoneNumber.equals(initialPhoneNumber)
                            && modifyCity.equals(initialCity) && modifySex.equals(initialSex) && modifyBirthday.equals(initialBirthday)
                            && modifyHeight.equals(initialHeight) && modifyWeight.equals(initialWeight))
                    {
                        isModify=false;
                        Log.d("修改","logData");
                    }
                    else isModify=true;
                    Sure();
                    break;
                case R.id.rl_set_avatar:
                    initChooseImage();
                    break;
                case R.id.set_sex_rl:
                    initSexPicker();
                    break;
                case R.id.set_city_rl:
                    initCityPicker();
                    cityPicker.show();
                    break;
                case R.id.set_birthday_rl:
                    initDatePicker();
                    break;
                case R.id.set_height_rl:
                    initHeightPicker();
                    break;
                case R.id.set_weight_rl:
                    initWeightPicker();
                    break;
                default:
                    break;
            }
        }
    }
}